#include "GroupIDGenerator.h"
#include "ConnectionPool.h"
#include "SqlQuery.h"
#include "Format.h"

GroupIDGenerator *GroupIDGenerator::globalInstance = new GroupIDGenerator();

GroupIDGenerator::GroupIDGenerator()
{
    // 初始化ID生成器，从数据库读取最大ID
    // 从数据库连接池获取一个mysql连接
    MYSQL *conn = ConnectionPool::getInstance()->getConnObj();
    SqlQuery query(conn);

    // 判断表是否是空的，因为select max(gid) from `group` 就算表为空，也会返回一行，获取空值时会报错
    string sql = "select count(*) from `group`";
    query.exec(sql);
    int count = atoi(query.getRes().front().front().data());
    if(count == 0)
        maxgId = 100000;
    else
    {
        // 查询最大ID
        sql = "select max(gid) from `group`";
        query.exec(sql);
        maxgId = atoi(query.getRes().front().front().data());
    }
    // 回收数据库连接
    ConnectionPool::getInstance()->recycleConnObj(conn);
}

GroupIDGenerator::~GroupIDGenerator()
{
}

int GroupIDGenerator::createGroupID()
{
    m_mutex.lock();
    int tmp = ++maxgId;
    m_mutex.unlock();
    return tmp;
}